﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Spring.Context;

using System.Xml;
using System.Data;
using System.Configuration;

namespace BookFinder
{
    public class SearchGoogleAPI : ISearchAPI
    {
        private String googleSearchURL = "https://www.googleapis.com/shopping/search/v1/public/products?key=";
        private String googleSearchAPIKey = "";
        private String googleSearchCountry = "US";
        private String googleSearchRestricted = "category%3ABooks";
        private String googleSearchResultFormat ="atom"; // or json

        public bool sendSearchQuery(String searchString, ref BooksCollection bc)
        {
            if ( ConfigurationManager.AppSettings["GoogleAccessKey"] != null)
                
            {
                googleSearchAPIKey = ConfigurationManager.AppSettings["GoogleAccessKey"];
            }
            else if(Environment.GetEnvironmentVariable("GOOGLE_API_KEY") != null)
            {
                googleSearchAPIKey = Environment.GetEnvironmentVariable("GOOGLE_API_KEY").ToString();
            }
            else
                return false;

            searchString += " book";
            String googleSearchString = googleSearchURL + googleSearchAPIKey + "&country=" + googleSearchCountry +
                "&q=" + searchString + "&alt=" + googleSearchResultFormat + "&restrictedBy=" + googleSearchRestricted;

            HttpGetter httpGetter = new HttpGetter();
            String response = httpGetter.HttpGetRequest(googleSearchString);

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(response);

            XmlNamespaceManager xmlManager = new XmlNamespaceManager(xmlDoc.NameTable);
            xmlManager.AddNamespace("s", "http://www.google.com/shopping/api/schemas/2010");

            XmlNodeList xmlBooks = xmlDoc.SelectNodes(@"//s:product", xmlManager);
                             
            //dt.NewRow();
            XmlNodeList tmpNodeList;
            //DataRow dr;

            foreach (XmlElement xmlElement in xmlBooks)
            {
                //dr = dt.NewRow();            
                Book newBook = new Book();

                newBook.DataSource = "Google";
                newBook.SearchSource = SearchSourceType.Google;

                tmpNodeList = xmlElement.SelectNodes("s:author/s:name", xmlManager);
                //dr[0] = tmpNodeList.Item(0).InnerText;
                if (tmpNodeList.Count != 0)
                    newBook.Vendor = tmpNodeList.Item(0).InnerText;


                tmpNodeList = xmlElement.SelectNodes("s:title", xmlManager);
                if (tmpNodeList.Count != 0)
                    //dr[1]  = tmpNodeList.Item(0).InnerText;
                    newBook.Title = tmpNodeList.Item(0).InnerText;

                tmpNodeList = xmlElement.SelectNodes("s:inventories/s:inventory/s:price", xmlManager);
                //dr[2] = tmpNodeList.Item(0).InnerText;
                if (tmpNodeList.Count != 0)
                {
                    string strPrice = tmpNodeList.Item(0).InnerText;
                    if (strPrice[0] == '$')
                    {
                        strPrice = strPrice.Remove(0, 1);
                    }

                    newBook.Price = Decimal.Parse(strPrice);

                }

                tmpNodeList = xmlElement.SelectNodes("s:gtin", xmlManager);
                if (tmpNodeList.Count != 0)
                    //dr[3] = tmpNodeList.Item(0).InnerText;                
                    newBook.ISBN = tmpNodeList.Item(0).InnerText;

                tmpNodeList = xmlElement.SelectNodes("s:description", xmlManager);
                if (tmpNodeList.Count != 0)
                    //dr[3] = tmpNodeList.Item(0).InnerText;                
                    newBook.Description = tmpNodeList.Item(0).InnerText;

                tmpNodeList = xmlElement.SelectNodes("s:link", xmlManager);
                if (tmpNodeList.Count != 0)
                       newBook.BookURL = tmpNodeList.Item(0).InnerText;

                tmpNodeList = xmlElement.SelectNodes("s:images/s:image", xmlManager);
                if (tmpNodeList.Count != 0 && tmpNodeList.Item(0).Attributes != null)
                    //dr[3] = tmpNodeList.Item(0).InnerText;                       
                    newBook.BookCoverURL = tmpNodeList.Item(0).Attributes.GetNamedItem("link").Value.ToString();

                // Do the Author Last 
                //searchString = googleSearchBookISBN + googleSearchBookISBNCriteria + newBook.ISBN + "&key=" + googleSearchAPIKey;
                //response = httpGetter.HttpGetRequest(searchString);                
                //xmlDoc.LoadXml(response);
                //xmlBooks = xmlDoc.SelectNodes(@"//s:author", xmlManager);

                newBook.ISBN = ISBNConverter.GetISBN13(newBook.ISBN);

                if (newBook.ISBN != "" && newBook.ISBN.Substring(0, 3) == "978")
                {
                    // google sometimes returns results which arent books,
                    // Books must start with a 978 ISBN13
                    bc.Add(newBook);
                }
            }

            return true;
        }        
    }    
}